import { reqCarList, reqDeleteCartByid, reqUpdateCheckedById } from "@/api"
const actions = {
    async getShopCartlist({ commit }) {
        let result = await reqCarList()
        if (result.code == 200) {
            commit("SHOPCARTLIST", result.data)
        }
    },
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartByid(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    async updatedCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    deleteAllCheckedCart({ dispatch, getters }) {
        //获取给我全部的产品，是也数组
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : '';
            PromiseAll.push(promise)
        });
        //全成功为返回成功，有一个失败返回失败
        return Promise.all(PromiseAll)
    },
    updatedAllCheckedById({dispatch,getters},checked){
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == checked ? "": dispatch('updatedCheckedById', {skuId:item.skuId,isChecked:checked}) ;
            PromiseAll.push(promise)
        });
        return Promise.all(PromiseAll)
    }
}
const mutations = {
    SHOPCARTLIST(state, cartList) {
        state.cartList = cartList
    }

}
const state = {
    cartList: []
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
}

export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}